package com.gh.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.gh.dto.ExcelDictDTO;
import com.gh.mapper.DictMapper;
import com.gh.service.DictService;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author Eric
 * @Date 2021/9/8 21:35
 * @Version 1.0
 */
@Slf4j
@NoArgsConstructor
public class ExcelDtoListener extends AnalysisEventListener<ExcelDictDTO> {

    private DictMapper dictMapper;

    public ExcelDtoListener(DictMapper dictMapper) {
        this.dictMapper = dictMapper;
    }

    private List<ExcelDictDTO> list = new ArrayList<>();

    private static final int COUNT_SIZE = 5;

    @Override
    public void invoke(ExcelDictDTO excelDictDTO, AnalysisContext analysisContext) {
        log.info("解析到一条数据：{}", excelDictDTO);
        list.add(excelDictDTO);
        if (list.size() >= COUNT_SIZE) {
            saveData();
            list.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        //最后把剩余的部分导入数据库
        saveData();
        log.info("数据解析完成");
    }

    private void saveData() {
        log.info("{} 条数据被存储到数据库...", list.size());
        dictMapper.insertBatch(list);
        log.info("{} 条数据存储到数据库成功...", list.size());
    }
}
